package com.supor.aiot.mine.utils;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.baseconfig.common.utils.ThreadUtils;
import com.supor.aiot.common.utils.AnimationUtil;
import com.supor.aiot.mine.R;

import java.lang.ref.WeakReference;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: FeedbackPop <br>
 * 作者: lei <br>
 * 日期: 2020/12/28 <br>
 */
public class TakePhotoPop {
    static PopupWindow photoPopupWindow;
    Handler handler;
    private WeakReference<Activity> activityReference;
    TakePhotoCallback callback;

    private static volatile TakePhotoPop instance;
    private float alpha;
    int duration = 300;
    int sleepTime = duration / 100;

    public static TakePhotoPop getInstance() {
        if (instance == null) {
            instance = new TakePhotoPop();
        }
        return instance;
    }

    private TakePhotoPop() {
    }

    public void init(Activity activity, TakePhotoCallback callback) {
        handler = new Handler(activity.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    AnimationUtil.backgroundAlpha(activityReference.get(), (float) msg.obj);
                }
            }
        };
        this.callback = callback;
        activityReference = new WeakReference<>(activity);
        initPop(activity);
    }

    public void setCallback(TakePhotoCallback callback) {
        this.callback = callback;
    }

    private void initPop(Activity activity) {
        View view = LayoutInflater.from(activity).inflate(R.layout.pop_take_photo, null);
        setPopupWindow(photoPopupWindow = new PopupWindow(), view);

        TextView tvCamera = view.findViewById(R.id.tv_camera);
        tvCamera.setOnClickListener(v -> {
            dismissPhotoPop();
            if (callback != null) {
                callback.onSelect(v, 1);
            }
        });
        TextView tvPhoto = view.findViewById(R.id.tv_photo);
        tvPhoto.setOnClickListener(v -> {
            dismissPhotoPop();
            if (callback != null) {
                callback.onSelect(v, 2);
            }
        });
        Button btnCancel = view.findViewById(R.id.btn_cancel);
        btnCancel.setOnClickListener(v -> dismissPhotoPop());

    }

    /**
     * 设置popwindow属性
     *
     * @param popupWindow
     * @param view
     */
    private void setPopupWindow(PopupWindow popupWindow, View view) {
        popupWindow.setContentView(view);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(null);
        popupWindow.setFocusable(false);// 解决点击view重新打开popwindow的问题
        popupWindow.setOutsideTouchable(true);// 点击外部popupwindow消失
        popupWindow.setAnimationStyle(R.style.privacy_popup_window_anim);
        // 退出popupWindow时取消暗背景
        popupWindow.setOnDismissListener(this::processDismiss);
    }

    // popwindow消失时背景同步变化
    private void processDismiss() {
        ThreadUtils.execute(() -> {
            while (alpha < 1f) {
                try {
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message msg = handler.obtainMessage();
                msg.what = 1;
                alpha += 0.005f;
                msg.obj = alpha;
                handler.sendMessage(msg);
            }
        });
    }

    public void showPhotoPop(Activity activity, View rootView) {
        if (photoPopupWindow == null) {
            initPop(activity);
        }
        photoPopupWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
        showAnimation();
    }

    private void showAnimation() {
        alpha = 1f;
        ThreadUtils.execute(() -> {
            while (alpha > 0.5f) {
                try {
                    // 根据弹出动画时间和减少的透明度计算时间
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message msg = handler.obtainMessage();
                msg.what = 1;
                // 每次减少0.005，精度越高，变暗的效果越流畅
                alpha -= 0.005f;
                msg.obj = alpha;
                handler.sendMessage(msg);
            }
        });
    }

    public boolean isPhotoPopShow() {
        return photoPopupWindow != null && photoPopupWindow.isShowing();
    }

    public void dismissPhotoPop() {
        if (photoPopupWindow != null && photoPopupWindow.isShowing()) {
            photoPopupWindow.dismiss();
        }
    }

    public interface TakePhotoCallback {
        /**
         * @param position 点击位置: 0-取消|1-拍照|2-相册
         */
        void onSelect(View v, int position);
    }
}
